<template>
  <div class="header">
    <h1>Manual Git</h1>
    <div class="controls">
      <div class="directory-selector">
        <span>工作目录: {{ currentDirectory || '未选择' }}</span>
        <button @click="selectDirectory">选择目录</button>
      </div>

      <div class="command-input">
        <input
          v-model="command"
          placeholder="输入 git 命令，如 status, pull, commit -m 'message'..."
          @keyup.enter="executeCommand"
        />
        <button :disabled="!currentDirectory" @click="executeCommand">执行</button>
      </div>

      <div class="quick-actions">
        <button :title="GitCommand.status.label" @click="runCommand(GitCommand.status.command)">
          {{ GitCommand.status.name }}
        </button>
        <button :title="GitCommand.pull.label" @click="runCommand(GitCommand.pull.command)">
          {{ GitCommand.pull.name }}
        </button>
        <button :title="GitCommand.commit.label" @click="runCommand(GitCommand.commit.command)">
          {{ GitCommand.commit.name }}
        </button>
        <button :title="GitCommand.push.label" @click="runCommand(GitCommand.push.command)">
          {{ GitCommand.push.name }}
        </button>
        <button
          :title="GitCommand.commitPush.label"
          @click="runCommand(GitCommand.commitPush.command)"
        >
          {{ GitCommand.commitPush.name }}
        </button>
      </div>
    </div>
  </div>

  <div class="terminal-output">
    <div v-for="(line, index) in outputLines" :key="index" :class="line.type">
      <span class="date">{{ line.timestamp }}: </span>
      <span v-if="line.type === 'command'">$ git {{ line.data }}</span>
      <span v-else>{{ line.data }}</span>
    </div>

    <div v-if="isExecuting" class="executing-indicator">
      <div class="spinner"></div>
      <span>执行中...</span>
    </div>
  </div>

  <div class="command-history">
    <h3>命令历史</h3>
    <ul>
      <li v-for="(cmd, index) in commandHistory" :key="index">
        <button @click="runHistoryCommand(cmd)">$ git {{ cmd }}</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { GitCommand } from './js/enum/GitCommand'

const currentDirectory = ref('')
const command = ref('')
const outputLines = ref([])
const isExecuting = ref(false)

// 选择工作目录
const selectDirectory = async () => {
  const dir = await window.electronAPI.selectDirectory()
  if (dir) {
    currentDirectory.value = dir
    addOutputLine(`工作目录已设置为: ${dir}`, 'info')
  }
}

// 快捷执行命令 (核心实现)
const runCommand = (gitCommand) => {
  console.log('runCommand==========', gitCommand)
  if (!currentDirectory.value) {
    addOutputLine('请先选择工作目录', 'error')
    return
  }
  // 处理带参数的命令
  if (typeof gitCommand === 'string') {
    command.value = gitCommand
  }
  // 处理对象形式的复杂命令
  else if (typeof gitCommand === 'object') {
    command.value = gitCommand.command
    if (gitCommand.confirm && !confirm(gitCommand.message)) {
      return
    }
  } else {
    // 弹出错误提示
    addOutputLine('请输入正确的命令', 'error')
  }
  executeCommand()
}

// 监听实时输出
const outputHandler = (data) => {
  addOutputLine(data.data, data.type)
}

onMounted(() => {
  window.electronAPI.onGitOutput(outputHandler)
})

onUnmounted(() => {
  window.electronAPI.onGitOutput(null)
})

// 执行 Git 命令
const executeCommand = async () => {
  const fullCommand = command.value.trim()
  if (!fullCommand || !currentDirectory.value) return

  isExecuting.value = true
  const [cmd, ...args] = fullCommand.split(/\s+/).filter((arg) => arg)

  // 显示命令
  addOutputLine(fullCommand, 'command')

  try {
    // 执行命令
    await window.electronAPI.executeGit(cmd, args, currentDirectory.value)
  } catch (error) {
    addOutputLine(`命令执行失败: ${error.errorOutput || error.error || '未知错误'}`, 'stderr')
  } finally {
    isExecuting.value = false
    command.value = ''
  }
}

// 添加输出行
const addOutputLine = (data, type) => {
  const lines = data.split('\n')
  lines.forEach((line) => {
    if (line.trim()) {
      outputLines.value.push({
        type,
        data: line,
        timestamp: new Date().toLocaleTimeString()
      })
    }
  })

  // 限制输出行数
  if (outputLines.value.length > 200) {
    outputLines.value.splice(0, outputLines.value.length - 200)
  }

  // 滚动到底部
  setTimeout(() => {
    const terminal = document.querySelector('.terminal-output')
    if (terminal) terminal.scrollTop = terminal.scrollHeight
  }, 10)
}

// 初始化
onMounted(() => {
  addOutputLine('欢迎使用 Auto Git 终端', 'info')
  addOutputLine('请先选择工作目录', 'info')
})
</script>

<style scoped></style>
